const api = require('../../utils/api.js');

Page({
  data: {
    userInfo: {
      username: '',
      gender: 0, // 0-未选择 1-男 2-女
      age: '',
      height: '',
      weight: '',
      target: -1 // -1-未选择 0-增肥 1-养生 2-减肥
    },
    genderList: ['男', '女'],
    targetList: ['增肥', '养生', '减肥'],
    ageList: Array.from({ length: 100 }, (_, i) => `${i + 1}岁`), // 1-100岁
    heightList: Array.from({ length: 111 }, (_, i) => `${i + 100}cm`), // 100-210cm
    weightList: Array.from({ length: 141 }, (_, i) => `${i + 30}kg`), // 30-170kg
    
    isSubmitting: false
  },

  onLoad: function(options) {
    // 检查是否已登录
    let openid = wx.getStorageSync('openid');
    if (!openid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/login/login'
        });
      }, 2000);
      return;
    }

    // 获取用户授权信息（如果有）
    let userProfile = wx.getStorageSync('userProfile');
    if (userProfile) {
      this.setData({
        'userInfo.username': userProfile.nickName || '',
        'userInfo.gender': userProfile.gender || 0
      });
    }
  },

  // 输入用户名
  inputUsername: function(e) {
    this.setData({
      'userInfo.username': e.detail.value
    });
  },

  // picker 选择器事件
  onGenderPickerChange: function(e) {
    const index = parseInt(e.detail.value);
    this.setData({
      'userInfo.gender': index + 1 // 1-男 2-女
    });
  },
  
  onAgePickerChange: function(e) {
    const index = parseInt(e.detail.value);
    // ageList 中的值是 "1岁"、"2岁"，需要提取数字
    this.setData({
      'userInfo.age': index + 1 // 因为 index 从 0 开始，所以 +1 得到实际年龄
    });
  },
  
  onHeightPickerChange: function(e) {
    const index = parseInt(e.detail.value);
    // heightList 中的值是 "100cm"、"101cm"，需要提取数字
    this.setData({
      'userInfo.height': index + 100 // 因为身高从 100cm 开始
    });
  },
  
  onWeightPickerChange: function(e) {
    const index = parseInt(e.detail.value);
    // weightList 中的值是 "30kg"、"31kg"，需要提取数字
    this.setData({
      'userInfo.weight': index + 30 // 因为体重从 30kg 开始
    });
  },
  
  onTargetPickerChange: function(e) {
    const index = parseInt(e.detail.value);
    this.setData({
      'userInfo.target': index
    });
  },

  // 提交注册信息
  submitRegister: function() {
    const that = this;
    const { userInfo } = that.data;

    // 验证必填项
    if (!userInfo.username || !userInfo.username.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    if (!userInfo.gender) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    if (!userInfo.age || userInfo.age <= 0) {
      wx.showToast({
        title: '请选择年龄',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    if (!userInfo.height || userInfo.height <= 0) {
      wx.showToast({
        title: '请选择身高',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    if (!userInfo.weight || userInfo.weight <= 0) {
      wx.showToast({
        title: '请选择体重',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    if (userInfo.target < 0) {
      wx.showToast({
        title: '请选择健康目标',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    that.setData({
      isSubmitting: true
    });

    wx.showLoading({
      title: '提交中...',
      mask: true
    });

    // 发送注册信息到后端
    wx.request({
      url: api.register(),
      method: 'POST',
      data: {
        username: userInfo.username.trim(),
        gender: userInfo.gender,
        age: parseInt(userInfo.age),
        height: parseFloat(userInfo.height),
        weight: parseFloat(userInfo.weight),
        target: userInfo.target
      },
      success: (res) => {
        wx.hideLoading();
        that.setData({
          isSubmitting: false
        });

        if (res.data.success) {
          wx.showToast({
            title: '注册成功！',
            icon: 'success',
            duration: 2000
          });

          // 跳转到首页
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/index/index'
            });
          }, 2000);
        } else {
          wx.showToast({
            title: res.data.message || '注册失败',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        that.setData({
          isSubmitting: false
        });

        console.error('注册请求失败:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  }
})

